/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */
package com.pig4cloud.pigx.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pigx.common.core.constant.SecurityConstants;
import com.pig4cloud.pigx.common.core.constant.enums.*;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.core.util.wechat.WechatUtils;
import com.pig4cloud.pigx.order.api.entity.*;
import com.pig4cloud.pigx.order.api.vo.OrderDeliveryVO;
import com.pig4cloud.pigx.order.api.vo.OrderInfoVO;
import com.pig4cloud.pigx.order.mapper.OrderInfoMapper;
import com.pig4cloud.pigx.order.service.*;
import com.pig4cloud.pigx.shop.api.entity.GoodsGift;
import com.pig4cloud.pigx.shop.api.feign.RemoteGoodsGiftService;
import com.pig4cloud.pigx.shop.api.feign.RemoteGoodsSpuService;
import com.pig4cloud.pigx.shop.api.vo.GoodsSkuVO;
import com.pig4cloud.pigx.shop.api.vo.GoodsSpuVO;
import com.pig4cloud.pigx.shop.user.api.dto.CustomToUserOrderSummaryDTO;
import com.pig4cloud.pigx.shop.user.api.entity.*;
import com.pig4cloud.pigx.shop.user.api.feign.*;
import com.pig4cloud.pigx.shop.user.api.vo.CustomToUserOrderSummaryVO;
import com.pig4cloud.pigx.shop.user.api.vo.ShopEquityVO;
import com.pig4cloud.pigx.shop.user.api.vo.ShopUserCouponVO;
import com.pig4cloud.pigx.shop.user.api.vo.ShopUserVO;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 订单管理
 *
 * @author pigx code generator
 * @date 2023-12-06 22:47:34
 */
@Service
@Slf4j
@AllArgsConstructor
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {

	private final OrderSkuDetailService orderSkuDetailService;

	private final OrderGiftDetailService orderGiftDetailService;

	private final RemoteShopUserService remoteShopUserService;

	private final RemoteShopCouponService remoteShopCouponService;

	private final RemoteGoodsSpuService remoteGoodsSpuService;

	private final OrderDeliveryService orderDeliveryService;

	private final DeliveryService deliveryService;

	private final RedisTemplate redisTemplate;

	private final RocketMQTemplate rocketMQTemplate;

	private final RemoteShopUserPointChangeRecordService remoteShopUserPointChangeRecordService;

	private final RemoteShopUserPointPolicyService remoteShopUserPointPolicyService;

	private final RemoteGoodsGiftService remoteGoodsGiftService;

	private final OrderSkuPointPolicyService orderSkuPointPolicyService;

	private final RemoteShopUserMoneyChangeRecordService remoteShopUserMoneyChangeRecordService;

	private final RemoteShopEquityService remoteShopEquityService;

	/**
	 * c端创建订单
	 * @param orderVO
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public R create(OrderInfoVO orderVO) {
		// 获取sku信息
		getOrderDetail(orderVO);
		// 获取礼品信息
		getOrderGift(orderVO);
		// 获取优惠券信息
		getOrderCoupon(orderVO);

		// 判断是否能创建订单
		R checkResult = this.checkCreateOrder(orderVO);
		if (checkResult.getCode() == 1) {
			return checkResult;
		}
		// 获取总积分和总分润
		getTotalProfit(orderVO);
		// 创建订单
		OrderInfo order = new OrderInfo();
		BeanUtils.copyProperties(orderVO, order);
		this.save(order);
		Long orderId = order.getId();

		// 添加商品sku订单详情
		saveSkuDetails(orderVO.getSkuDetails(), orderId);

		// 添加礼品订单详情
		saveGiftDetails(orderVO.getGiftDetails(), orderId);

		// 添加积分策略
		saveSkuPointPolicy(orderVO.getSkuPointPolicies(), orderId);

		// 回传订单ID
		orderVO.setId(orderId);

		// 订单ID写入缓存
		log.info("添加缓存订单:" + orderId.toString());
		String key = "shop_order_" + orderId.toString();
		// 12分钟过期
		redisTemplate.opsForValue().set(key, key, 720, TimeUnit.SECONDS);
		log.info("写入缓存订单:" + orderId.toString());

		// 发送mq处理订单未支付过期
		log.info("发送订单消息:" + orderId.toString());
		Message<String> message = MessageBuilder.withPayload(orderId.toString()).build();
		rocketMQTemplate.syncSend("shop-order-pay-time-out", message, 10000, 14);
		log.info("订单消息发送成功:" + orderId.toString());

		return R.ok(orderVO);
	}

	/**
	 * 获取订单sku信息
	 * @param orderVO
	 */
	private void getOrderDetail(OrderInfoVO orderVO) {
		if (orderVO.getSkuDetails().size() > 0) {
			orderVO.getSkuDetails().forEach(sku -> {
				if (orderVO.getOrderType().equals(OrderTypeEnum.SKU.getType())) {
					// 商品订单的场合
					R<GoodsSpuVO> goodsSpuVOR = remoteGoodsSpuService.getSimpleSkuById(sku.getSpuId(), sku.getSkuId(),
							SecurityConstants.FROM_IN);
					GoodsSpuVO goodsSpuVO = goodsSpuVOR.getData();
					if (goodsSpuVO != null && goodsSpuVO.getSkus().size() > 0) {
						GoodsSkuVO skuVO = goodsSpuVO.getSkus().get(0);
						sku.setSkuName(skuVO.getSkuName());
						sku.setSkuShortName(skuVO.getSkuShortName());
						sku.setPointPolicyId(skuVO.getPointPolicyId());
						sku.setFirstProfitPolicyId(skuVO.getFirstProfitPolicyId());
						sku.setSecondProfitPolicyId(skuVO.getSecondProfitPolicyId());
						sku.setSellPrice(skuVO.getSellPrice());
						sku.setMarketPrice(skuVO.getMarketPrice());
						sku.setBasePrice(skuVO.getBasePrice());
						sku.setCanningCount(skuVO.getCanningCount());
						sku.setBagCount(skuVO.getBagCount());
						sku.setStripCount(skuVO.getStripCount());
					}
				}
				else if (orderVO.getOrderType().equals(OrderTypeEnum.EQUITY.getType())) {
					// 权益包的场合
					R<ShopEquityVO> shopEquityVOR = remoteShopEquityService.getShopEquityInnerDetail(sku.getSpuId(),
							SecurityConstants.FROM_IN);
					ShopEquityVO shopEquityVO = shopEquityVOR.getData();
					if (shopEquityVO != null) {
						sku.setSkuName(shopEquityVO.getEquityName());
						sku.setSkuShortName(shopEquityVO.getEquityShortName());
						sku.setPointPolicyId(shopEquityVO.getPointPolicyId());
						sku.setSellPrice(shopEquityVO.getSellPrice());
						sku.setMarketPrice(shopEquityVO.getSellPrice());
						sku.setBasePrice(shopEquityVO.getSellPrice());
						sku.setCanningCount(0);
						sku.setBagCount(0);
						sku.setStripCount(0);
					}
				}

			});
		}
	}

	/**
	 * 获取订单sku对应的礼品
	 * @param orderVO
	 */
	private void getOrderGift(OrderInfoVO orderVO) {
		if (orderVO.getGiftDetails() != null && orderVO.getGiftDetails().size() > 0) {
			orderVO.getGiftDetails().forEach(gift -> {
				R<GoodsGift> goodsGiftR = remoteGoodsGiftService.getGiftInfoById(gift.getGiftId(),
						SecurityConstants.FROM_IN);
				GoodsGift goodsGift = goodsGiftR.getData();
				if (goodsGift != null) {
					gift.setGiftName(goodsGift.getGiftName());
					gift.setBrand(goodsGift.getBrand());
					gift.setOrigin(goodsGift.getOrigin());
					gift.setSpecs(goodsGift.getSpecs());
					gift.setSize(goodsGift.getSize());
					gift.setColor(goodsGift.getColor());
					gift.setSendType(goodsGift.getSendType());
				}
			});
		}
	}

	/**
	 * 获取优惠券信息
	 * @param orderVO
	 */
	private void getOrderCoupon(OrderInfoVO orderVO) {
		if (orderVO.getCoupons() != null && orderVO.getCoupons().size() > 0) {
			orderVO.getCoupons().forEach(coupon -> {
				// 获取优惠券信息
				R<ShopCoupon> couponR = remoteShopCouponService.getCouponInfoById(coupon.getCouponId(),
						SecurityConstants.FROM_IN);
				ShopCoupon shopCoupon = couponR.getData();
				if (shopCoupon != null) {
					// BeanUtils.copyProperties(shopCoupon, coupon);
					coupon.setCouponName(shopCoupon.getCouponName());
					coupon.setOrderPrice(shopCoupon.getOrderPrice());
					coupon.setCouponType(shopCoupon.getCouponType());
					coupon.setCouponCate(shopCoupon.getCouponCate());
					coupon.setDiscountRate(shopCoupon.getDiscountRate());
					coupon.setDeductionPrice(shopCoupon.getDeductionPrice());
					coupon.setPoint(shopCoupon.getPoint());
				}
			});
		}
	}

	/**
	 * 判断是否能够创建订单
	 * @param orderVO
	 * @return
	 */
	private R checkCreateOrder(OrderInfoVO orderVO) {
		Long shopUserId = orderVO.getShopUserId();
		// 获取用户信息
		R<ShopUserVO> shopUserInfoInner = remoteShopUserService.getShopUserInfoInner(shopUserId,
				SecurityConstants.FROM_IN);
		ShopUserVO shopUserVO = shopUserInfoInner.getData();
		if (shopUserVO == null) {
			return R.failed("用户不存在，无法下单");
		}

		// 设置销售员ID
		orderVO.setSalesShopUserId(shopUserVO.getSalesShopUserId());

		// 判断是否存在订单详情
		if (orderVO.getSkuDetails().size() <= 0) {
			return R.failed("未选择购买的商品，无法下单");
		}

		orderVO.setChannelCode(shopUserVO.getChannelCode());
		orderVO.setParentId(shopUserVO.getParentId());
		// orderVO.setOrderType(OrderTypeEnum.GENERAL.getType());
		orderVO.setOrderStatus(OrderStatusEnum.PENDING.getType());
		orderVO.setNickName(shopUserVO.getNickName());
		// 存在优惠券的场合
		if (orderVO.getCoupons() != null && orderVO.getCoupons().size() > 0) {
			List<String> couponIds = new ArrayList<>();
			for (ShopUserCouponVO vo : orderVO.getCoupons()) {
				// 获取优惠券信息
				Long shopUserCouponId = vo.getId();
				// 判断优惠券是否可用
				ShopUserCoupon shopUserCoupon = new ShopUserCoupon();
				shopUserCoupon.setShopUserId(shopUserId);
				// 换成用户领取优惠券记录id
				shopUserCoupon.setId(shopUserCouponId);
				R couponStatue = remoteShopCouponService.checkUserCouponStatue(shopUserCoupon,
						SecurityConstants.FROM_IN);
				if (couponStatue.getCode() == 1) {
					return couponStatue;
				}
				couponIds.add(shopUserCouponId.toString());
			}
			if (couponIds.size() > 0) {
				// 保存优惠券ID
				orderVO.setCouponIds(String.join(",", couponIds));
			}
		}
		return R.ok();
	}

	/**
	 * 获取分润总额
	 */
	private void getTotalProfit(OrderInfoVO orderInfoVO) {
		// 获取总积分
		AtomicInteger totalPoint = new AtomicInteger();
		AtomicInteger totalFirstProfit = new AtomicInteger();
		AtomicInteger totalSecondProfit = new AtomicInteger();
		List<OrderSkuDetail> skuDetails = orderInfoVO.getSkuDetails();

		List<Long> pointPolicyIds = new ArrayList<>();
		skuDetails.forEach(sku -> {
			pointPolicyIds.add(sku.getPointPolicyId());
		});

		// 获取积分策略列表
		if (pointPolicyIds.size() > 0) {
			orderInfoVO.setSkuPointPolicies(new ArrayList<>());
			R<List<ShopUserPointPolicy>> pointPolicyResult = remoteShopUserPointPolicyService
					.getPointPolicyByIds(pointPolicyIds, SecurityConstants.FROM_IN);
			List<ShopUserPointPolicy> pointPolicyList = pointPolicyResult.getData();
			pointPolicyList.forEach(pointPolicy -> {
				// 判断积分策略类型
				if (pointPolicy.getPolicyType().equals(PointPolicyTypeEnum.FIX_POINT.getType())) {
					// 固定积分的场合
					totalPoint.addAndGet(pointPolicy.getPointRegular());
				}
				else if (pointPolicy.getPolicyType().equals(PointPolicyTypeEnum.PAY_RATIO.getType())) {
					// 按商品支付金额
					int point = orderInfoVO.getOrderPrice() * (pointPolicy.getPointRatio() / 100) / 100;
					totalPoint.addAndGet(point);
				}
				else if (pointPolicy.getPolicyType().equals(PointPolicyTypeEnum.SELL_PRICE_RATIO.getType())) {
					// 按商品销售价格
					int point = orderInfoVO.getSourceOrderPrice() * (pointPolicy.getPointRatio() / 100) / 100;
					totalPoint.addAndGet(point);
				}
				OrderSkuPointPolicy orderSkuPointPolicy = new OrderSkuPointPolicy();
				orderSkuPointPolicy.setPolicyName(pointPolicy.getPolicyName());
				orderSkuPointPolicy.setPolicyType(pointPolicy.getPolicyType());
				orderSkuPointPolicy.setPointRegular(pointPolicy.getPointRegular());
				orderSkuPointPolicy.setPointRatio(pointPolicy.getPointRatio());
				orderSkuPointPolicy.setOrderPrice(pointPolicy.getOrderPrice());
				orderInfoVO.getSkuPointPolicies().add(orderSkuPointPolicy);
			});
		}

		// 判断优惠券是否存在积分
		if (orderInfoVO.getCoupons() != null && orderInfoVO.getCoupons().size() > 0) {
			orderInfoVO.getCoupons().forEach(coupon -> {
				// 获取优惠券
				if (coupon.getPoint() != null) {
					totalPoint.addAndGet(coupon.getPoint());
				}
			});
		}
		orderInfoVO.setTotalPoint(totalPoint.get());
		orderInfoVO.setTotalFirstProfit(totalFirstProfit.get());
		orderInfoVO.setTotalSecondProfit(totalSecondProfit.get());
	}

	/**
	 * 添加商品sku订单详情
	 * @param skuDetails
	 * @param orderId
	 */
	private void saveSkuDetails(List<OrderSkuDetail> skuDetails, Long orderId) {
		if (skuDetails.size() > 0) {
			skuDetails.forEach(sku -> {
				sku.setOrderId(orderId);
			});
			orderSkuDetailService.saveBatch(skuDetails);
		}
	}

	/**
	 * 添加订单礼品详情
	 * @param giftDetails
	 * @param orderId
	 */
	private void saveGiftDetails(List<OrderGiftDetail> giftDetails, Long orderId) {
		if (giftDetails != null && giftDetails.size() > 0) {
			giftDetails.forEach(gift -> {
				gift.setOrderId(orderId);
			});
			orderGiftDetailService.saveBatch(giftDetails);
		}
	}

	/**
	 * 添加积分策略记录
	 * @param orderSkuPointPolicies
	 * @param orderId
	 */
	private void saveSkuPointPolicy(List<OrderSkuPointPolicy> orderSkuPointPolicies, Long orderId) {
		if (orderSkuPointPolicies != null && orderSkuPointPolicies.size() > 0) {
			orderSkuPointPolicies.forEach(item -> {
				item.setOrderId(orderId);
			});
			orderSkuPointPolicyService.saveBatch(orderSkuPointPolicies);
		}
	}

	/**
	 * 通过订单ID获取订单详情
	 * @param shopUserId
	 * @param orderId
	 * @return
	 */
	@Override
	public R getOrderInfo(Long shopUserId, Long orderId) {
		OrderInfoVO result = new OrderInfoVO();

		// 获取订单信息
		OrderInfo orderInfo = this.getById(orderId);
		if (orderInfo == null) {
			return R.failed("订单不存在");
		}

		BeanUtils.copyProperties(orderInfo, result);

		// 待支付的场合
		if (result.getOrderStatus().equals(OrderStatusEnum.PENDING.getType())) {
			// 用户下单时间
			LocalDateTime createTime = result.getCreateTime();
			LocalDateTime localDateTime = createTime.plusMinutes(10);
			// 获取用户下单时间的时间戳
			long endPayTimeSpan = localDateTime.toEpochSecond(ZoneOffset.ofHours(8));

			// 当前系统时间的时间戳
			Date date = new Date();
			long time = date.getTime();
			String timeStr = String.valueOf(time);
			// 获取当前系统时间的时间戳
			long nowTimeSpan = Long.parseLong(timeStr.substring(0, timeStr.length() - 3));

			// 计算剩余时间
			long residuePayTimeSpan = endPayTimeSpan - nowTimeSpan;
			result.setResiduePayTimeSpan(residuePayTimeSpan * 1000);
			log.info("未支付的订单号: {}，计算剩余时间: {}", result.getId(), residuePayTimeSpan);
		}

		// 获取订单商品sku详情
		LambdaQueryWrapper<OrderSkuDetail> lqwOrderSkuDetail = new LambdaQueryWrapper<>();
		lqwOrderSkuDetail.eq(OrderSkuDetail::getOrderId, orderId);
		List<OrderSkuDetail> skuDetails = orderSkuDetailService.list(lqwOrderSkuDetail);
		result.setSkuDetails(skuDetails);

		// 获取订单礼品详情
		LambdaQueryWrapper<OrderGiftDetail> lqwOrderGiftDetail = new LambdaQueryWrapper<>();
		lqwOrderGiftDetail.eq(OrderGiftDetail::getOrderId, orderId);
		List<OrderGiftDetail> giftDetails = orderGiftDetailService.list(lqwOrderGiftDetail);
		result.setGiftDetails(giftDetails);

		// 判断订单状态是否是发货
		if (Integer.parseInt(orderInfo.getOrderStatus()) >= Integer.parseInt(OrderStatusEnum.SHIPPED.getType())) {
			result.setOrderDeliveries(new ArrayList<>());
			// 查询物流信息
			LambdaQueryWrapper<OrderDelivery> lqwOrderDelivery = new LambdaQueryWrapper<>();
			lqwOrderDelivery.eq(OrderDelivery::getOrderId, orderId);
			List<OrderDelivery> orderDeliveries = orderDeliveryService.list(lqwOrderDelivery);
			// 获取物流名称
			orderDeliveries.forEach(item -> {
				OrderDeliveryVO orderDeliveryVO = new OrderDeliveryVO();
				BeanUtils.copyProperties(item, orderDeliveryVO);
				Delivery delivery = deliveryService.getById(item.getDeliveryId());
				if (delivery != null) {
					orderDeliveryVO.setDeliveryName(delivery.getDeliveryName());
				}
				result.getOrderDeliveries().add(orderDeliveryVO);
			});
		}

		return R.ok(result);
	}

	/**
	 * 根据订单号获取订单详情
	 * @param orderId
	 * @return
	 */
	@Override
	public OrderInfoVO getOrderInfoByOrderId(Long orderId) {
		// 订单信息
		OrderInfoVO result = new OrderInfoVO();
		OrderInfo orderInfo = this.getById(orderId);
		BeanUtils.copyProperties(orderInfo, result);

		// 订单详情
		List<OrderSkuDetail> skuDetails = orderSkuDetailService
				.list(Wrappers.<OrderSkuDetail>lambdaQuery().eq(OrderSkuDetail::getOrderId, orderId));
		result.setSkuDetails(skuDetails);

		// 礼品信息
		List<OrderGiftDetail> giftDetails = orderGiftDetailService
				.list(Wrappers.<OrderGiftDetail>lambdaQuery().eq(OrderGiftDetail::getOrderId, orderId));
		result.setGiftDetails(giftDetails);

		// 用户信息
		R<ShopUserVO> shopUser = remoteShopUserService.getShopUserInfoInner(result.getShopUserId(),
				SecurityConstants.FROM_IN);
		result.setShopUser(shopUser.getData());

		// 优惠券信息
		result.setCoupons(new ArrayList<>());
		if (!StringUtils.isEmpty(result.getCouponIds())) {
			// 存在优惠券的场合
			String[] couponIds = result.getCouponIds().split(",");
			for (String shopUserCouponId : couponIds) {
				R<ShopCoupon> info = remoteShopCouponService
						.getCouponInfoByShopUserCouponId(Long.parseLong(shopUserCouponId), SecurityConstants.FROM_IN);
				if (info.getData() != null) {
					ShopUserCouponVO shopCouponVO = new ShopUserCouponVO();
					BeanUtils.copyProperties(info.getData(), shopCouponVO);
					result.getCoupons().add(shopCouponVO);
				}
			}
		}

		// 获取业代信息
		if (result.getSalesShopUserId() != null) {
			R<ShopUserVO> salesShopUser = remoteShopUserService.getShopUserInfoInner(result.getSalesShopUserId(),
					SecurityConstants.FROM_IN);
			result.setSalesShopUser(salesShopUser.getData());
		}

		return result;
	}

	/**
	 * c端分页获取订单列表
	 * @param page
	 * @param orderInfo
	 * @return
	 */
	@Override
	public IPage getOrderPageList(Page page, OrderInfo orderInfo) {
		IPage<OrderInfoVO> result = new Page<>();
		Long shopUserId = orderInfo.getShopUserId();

		LambdaQueryWrapper<OrderInfo> lqwOrderInfo = new LambdaQueryWrapper<>();
		if (orderInfo.getShopUserId() != null) {
			lqwOrderInfo.eq(OrderInfo::getShopUserId, shopUserId);
		}
		if (orderInfo.getId() != null) {
			lqwOrderInfo.eq(OrderInfo::getId, orderInfo.getId());
		}
		if (!StringUtils.isEmpty(orderInfo.getOrderStatus())) {
			lqwOrderInfo.eq(OrderInfo::getOrderStatus, orderInfo.getOrderStatus());
		}
		if (!StringUtils.isEmpty(orderInfo.getContactNumber())) {
			lqwOrderInfo.like(OrderInfo::getContactNumber, orderInfo.getContactNumber());
		}
		lqwOrderInfo.orderByDesc(OrderInfo::getCreateTime);
		IPage<OrderInfo> items = this.page(page, lqwOrderInfo);
		if (items.getRecords().size() > 0) {
			List<Long> orderIds = new ArrayList<>();
			result = items.convert(u -> {
				OrderInfoVO v = new OrderInfoVO();
				BeanUtils.copyProperties(u, v);
				orderIds.add(u.getId());
				return v;
			});

			// 获取所有订单的sku
			LambdaQueryWrapper<OrderSkuDetail> lqwOrderSkuDetail = new LambdaQueryWrapper<>();
			lqwOrderSkuDetail.in(OrderSkuDetail::getOrderId, orderIds);
			List<OrderSkuDetail> skuDetailList = orderSkuDetailService.list(lqwOrderSkuDetail);

			// 获取所有订单对应的礼品
			LambdaQueryWrapper<OrderGiftDetail> lqwOrderGiftDetail = new LambdaQueryWrapper<>();
			lqwOrderGiftDetail.in(OrderGiftDetail::getOrderId, orderIds);
			List<OrderGiftDetail> giftDetailList = orderGiftDetailService.list(lqwOrderGiftDetail);

			result.getRecords().forEach(spu -> {
				// 添加sku信息
				List<OrderSkuDetail> skuDetails = skuDetailList.stream()
						.filter(p -> p.getOrderId().longValue() == spu.getId().longValue())
						.collect(Collectors.toList());
				spu.setSkuDetails(skuDetails);

				// 添加礼品信息
				List<OrderGiftDetail> giftDetails = giftDetailList.stream()
						.filter(p -> p.getOrderId().longValue() == spu.getId().longValue())
						.collect(Collectors.toList());
				spu.setGiftDetails(giftDetails);
			});
		}
		return result;

	}

	/**
	 * 支付成功回调
	 * @param orderInfo
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public R orderPaySuccess(OrderInfo orderInfo) {
		Long orderId = orderInfo.getId();
		// 获取订单信息
		OrderInfo order = this.getById(orderId);
		if (order == null) {
			log.info("订单不存在:" + orderId);
			return R.failed("订单不存在:" + orderId);
		}
		// 判断订单状态是不是待支付
		if (!order.getOrderStatus().equals(OrderStatusEnum.PENDING.getType())) {
			log.info("订单状态不是待支付状态:" + orderId);
			return R.failed("订单状态不是待支付状态:" + orderId);
		}
		OrderInfo record = new OrderInfo();
		record.setId(orderId);
		if (order.getOrderType().equals(OrderTypeEnum.SKU.getType())) {
			// 商品订单的场合,修改订单状态为待发货
			record.setOrderStatus(OrderStatusEnum.PROCESSED.getType());
		}
		else if (order.getOrderType().equals(OrderTypeEnum.EQUITY.getType())) {
			// 权益包的场合，修改订单状态为已完成
			record.setOrderStatus(OrderStatusEnum.COMPLETE.getType());
		}

		// 设置支付金额
		record.setPayPrice(orderInfo.getPayPrice());
		// 设置支付时间
		record.setPayTime(LocalDateTime.now());
		// 修改订单信息
		this.updateById(record);
		// 设置订单支付金额
		order.setPayPrice(orderInfo.getPayPrice());
		log.info("订单号:" + orderId + "已成功支付, 状态修改为待发货");

		// 抵扣优惠券
		if (!StringUtils.isEmpty(order.getCouponIds())) {
			log.info("抵扣优惠券,订单号ID:" + orderId + " 优惠券ID:" + order.getCouponIds());
			// 获取优惠券ID
			Long shopUserCouponId = Long.parseLong(order.getCouponIds());
			// 抵扣
			ShopUserCoupon shopUserCoupon = new ShopUserCoupon();
			shopUserCoupon.setShopUserId(order.getShopUserId());
			shopUserCoupon.setId(shopUserCouponId);
			shopUserCoupon.setOrderId(orderId);
			shopUserCoupon.setUseStatus(CouponUseStatusEnum.USED.getType());
			R result = remoteShopCouponService.useUserCoupon(shopUserCoupon, SecurityConstants.FROM_IN);
			if (result.getCode() == 0) {
				log.info("成功抵扣订单ID:" + orderId + " 抵扣优惠券ID:" + shopUserCouponId + " 用户ID:" + order.getShopUserId());
			}
			else {
				log.info("失败抵扣订单ID:" + orderId + " 抵扣优惠券ID:" + shopUserCouponId + " 用户ID:" + order.getShopUserId());
			}
		}

		// 添加积分记录
		if (order.getTotalPoint() != null && order.getTotalPoint() > 0L) {
			// 添加积分记录
			paySuccessUserPointChange(order);
		}

		// 添加自己分润记录

		// 添加上级分润记录

		// 修改用户总消费金额
		if (order.getPayPrice() != null && order.getPayPrice() > 0L) {
			// 增加消费金额
			handleUserOrderTotalChange(order, OperEnum.ADD.getType(), MoneyChangeRecordTypeEnum.PURCHASE.getType());
		}

		// 权益订单的场合
		if (order.getOrderType().equals(OrderTypeEnum.EQUITY.getType())) {
			handleShopEquityInfo(order);
		}

		return R.ok();
	}

	/**
	 * 支付成功后，积分变更处理
	 * @param order
	 */
	private void paySuccessUserPointChange(OrderInfo order) {
		// 获取订单详情
		String skuShortName = "";
		String skuBannerImages = "";
		List<OrderSkuDetail> orderSkuDetails = orderSkuDetailService
				.list(Wrappers.<OrderSkuDetail>lambdaQuery().eq(OrderSkuDetail::getOrderId, order.getId()));
		if (orderSkuDetails.size() > 0) {
			// 默认取第一个sku的信息
			if (order.getOrderType().equals(OrderTypeEnum.SKU.getType())) {
				skuShortName = orderSkuDetails.get(0).getSkuShortName();
			}
			else if (order.getOrderType().equals(OrderTypeEnum.EQUITY.getType())) {
				skuShortName = orderSkuDetails.get(0).getSkuName();
			}
			skuBannerImages = orderSkuDetails.get(0).getBannerImages();
		}

		// 添加积分上账记录
		ShopUserPointChangeRecord pointChangeRecord = new ShopUserPointChangeRecord();
		pointChangeRecord.setRecordName(skuShortName);
		pointChangeRecord.setRecordImages(skuBannerImages);
		if (order.getOrderType().equals(OrderTypeEnum.SKU.getType())) {
			// 购买商品
			pointChangeRecord.setRecordType(PointChangeSourceEnum.SHOP_MALL.getType());
		}
		else if (order.getOrderType().equals(OrderTypeEnum.EQUITY.getType())) {
			// 购买权益包
			pointChangeRecord.setRecordType(PointChangeSourceEnum.EQUITY_PACKAGE.getType());
		}
		pointChangeRecord.setShopUserId(order.getShopUserId());
		pointChangeRecord.setRecordOrderId(order.getId());
		pointChangeRecord.setStatus(PointChangeStatusEnum.PROCESSING.getType());
		pointChangeRecord.setOper(OperEnum.ADD.getType());
		pointChangeRecord.setPoint(order.getTotalPoint());
		R result = remoteShopUserPointChangeRecordService.addPointChange(pointChangeRecord, SecurityConstants.FROM_IN);
		if (result.getCode() == 0) {
			Long pointChangeRecordId = Long.parseLong(result.getData().toString());
			pointChangeRecord.setId(pointChangeRecordId);
			log.info("成功添加积分记录，订单号:" + order.getId() + "，积分抵扣记录ID:" + pointChangeRecordId);

			// 发送积分变更消息
			log.info("发送积分抵扣消息订单号ID:" + order.getId());
			rocketMQTemplate.convertAndSend("shop-user-point-change", pointChangeRecordId.toString());
			log.info("成功发送积分抵扣消息订单号ID:" + order.getId());
		}
		else {
			log.info("失败添加积分记录，订单号:" + order.getId());
		}
	}

	/**
	 * 支付成功后，消费总金额变更处理
	 */
	private void handleUserOrderTotalChange(OrderInfo order, String oper, String recordType) {
		// 获取订单详情
		String skuShortName = "";
		List<OrderSkuDetail> orderSkuDetails = orderSkuDetailService
				.list(Wrappers.<OrderSkuDetail>lambdaQuery().eq(OrderSkuDetail::getOrderId, order.getId()));
		if (orderSkuDetails.size() > 0) {
			// 默认取第一个sku的信息
			if (order.getOrderType().equals(OrderTypeEnum.SKU.getType())) {
				// 商品的场合取短名称
				skuShortName = orderSkuDetails.get(0).getSkuShortName();
			}
			else if (order.getOrderType().equals(OrderTypeEnum.EQUITY.getType())) {
				// 权益包的场合取权益包名称
				skuShortName = orderSkuDetails.get(0).getSkuName();
			}

		}

		ShopUserMoneyChangeRecord record = new ShopUserMoneyChangeRecord();
		record.setRecordName(skuShortName);
		record.setRecordType(recordType);
		record.setOperType(MoneyChangeOperTypeEnum.USE_ORDER_TOTAL.getType());
		record.setShopUserId(order.getShopUserId());
		record.setRecordOrderId(order.getId());
		record.setStatus(PointChangeStatusEnum.PROCESSING.getType());
		record.setOper(oper);
		record.setMoney(order.getPayPrice());
		R result = remoteShopUserMoneyChangeRecordService.addMoneyChange(record, SecurityConstants.FROM_IN);
		if (result.getCode() == 0) {
			Long moneyChangeRecordId = Long.parseLong(result.getData().toString());
			record.setId(moneyChangeRecordId);
			log.info("成功添加总金额记录，订单号:" + order.getId() + "，总金额记录ID:" + moneyChangeRecordId);

			// 发送积分变更消息
			log.info("发送总金额抵扣消息订单号ID:" + order.getId());
			rocketMQTemplate.convertAndSend("shop-user-money-change", moneyChangeRecordId.toString());
			log.info("成功发送总金额抵扣消息订单号ID:" + order.getId());
		}
		else {
			log.info("失败添加总金额记录，订单号:" + order.getId());
		}

	}

	/**
	 * 权益包的场合
	 */
	private void handleShopEquityInfo(OrderInfo order) {
		// 获取订单详情
		List<OrderSkuDetail> orderSkuDetails = orderSkuDetailService
				.list(Wrappers.<OrderSkuDetail>lambdaQuery().eq(OrderSkuDetail::getOrderId, order.getId()));
		orderSkuDetails.forEach(sku -> {
			Long equityId = sku.getSpuId();
			Long shopUserId = order.getShopUserId();
			// 发放权益
			ShopEquityVO vo = new ShopEquityVO();
			vo.setShopUserId(shopUserId);
			vo.setId(equityId);
			vo.setEquityOrderId(order.getId());
			R result = remoteShopEquityService.receiveShopEquity(vo, SecurityConstants.FROM_IN);
			if (result.getCode() == 0) {
				log.info("权益发放成功, 权益包ID:" + equityId + ", 用户ID:" + shopUserId);
			}
		});
	}

	/**
	 * 签收商品
	 * @param orderInfo
	 * @return
	 */
	@Override
	public R orderSingFor(OrderInfo orderInfo) {
		Long orderId = orderInfo.getId();
		Long shopUserId = orderInfo.getShopUserId();

		OrderInfo order = this.getOne(Wrappers.<OrderInfo>lambdaQuery().eq(OrderInfo::getId, orderId)
				.eq(OrderInfo::getShopUserId, shopUserId));
		if (order == null) {
			return R.failed("订单不存在");
		}
		OrderInfo record = new OrderInfo();
		record.setId(orderId);
		// 修改订单状态为待发货
		record.setOrderStatus(OrderStatusEnum.COMPLETE.getType());
		// 设置签收时间
		record.setReceiptTime(LocalDateTime.now());
		// 修改订单信息
		this.updateById(record);

		// 添加积分记录
		// 添加分润记录
		// todo
		// ShopUserBalanceRecord shopUserBalanceRecord = new ShopUserBalanceRecord();
		// shopUserBalanceRecord.setShopUserId(shopUserId);
		// shopUserBalanceRecord.setOrderId(orderId);
		// remoteShopUserBalanceRecordService.updateUserBalanceByOrderId(shopUserBalanceRecord,
		// SecurityConstants.FROM_IN);

		return R.ok();
	}

	/**
	 * 订单退款
	 * @param orderInfo
	 * @return
	 */
	@Override
	public R orderRefund(OrderInfo orderInfo) {
		Long orderId = orderInfo.getId();
		OrderInfo order = this.getById(orderId);
		if (order == null) {
			return R.failed("订单不存在");
		}
		try {
			String message = checkOrderRefund(order);
			if (!StringUtils.isEmpty(message)) {
				return R.failed(message);
			}

			Map<String, String> resMap = WechatUtils.xcxRefund(orderId.toString(), orderId.toString(),
					order.getPayPrice(), order.getPayPrice(), "REFUND_SOURCE_UNSETTLED_FUNDS");
			if ("SUCCESS".equals(resMap.get("returnCode")) && "OK".equals(resMap.get("returnMsg"))) {
				// 统一下单成功
				resMap.remove("returnCode");
				resMap.remove("returnMsg");
				log.info("【小程序支付服务】退款成功！");

				OrderInfo record = new OrderInfo();
				record.setId(orderId);
				// 修改订单状态为已退款
				record.setOrderStatus(OrderStatusEnum.REFUND.getType());
				// 设置退款时间
				record.setRefundTime(LocalDateTime.now());
				// 设置退款理由
				record.setRefundReason(orderInfo.getRefundReason());
				// 修改订单信息
				this.updateById(record);

				// 判断订单是否使用优惠券
				if (!StringUtils.isEmpty(order.getCouponIds())) {
					// 获取优惠券信息
					String[] couponIds = order.getCouponIds().split(",");
					for (String couponId : couponIds) {
						// 用户领取的优惠券Id
						Long shopUserCouponId = Long.parseLong(couponId);
						remoteShopCouponService.returnShopUserCoupon(shopUserCouponId, SecurityConstants.FROM_IN);
					}
				}

				// 减去用户总金额
				handleUserOrderTotalChange(order, OperEnum.SUB.getType(),
						MoneyChangeRecordTypeEnum.RETURN_CASH.getType());

				return R.ok(resMap);
			}
			else {
				log.info("【小程序支付服务】退款失败！原因:" + resMap.get("returnMsg"));
				return R.failed(resMap.get("returnMsg"));
			}
		}
		catch (Exception ex) {
			ex.printStackTrace();
			return R.failed("退款失败");
		}
	}

	/**
	 * 取消订单
	 * @param orderInfo
	 * @return
	 */
	@Override
	public R orderCancel(OrderInfo orderInfo) {

		OrderInfo order = this.getById(orderInfo.getId());
		// 判断订单是否存在
		if (order == null) {
			return R.ok("当前订单不存在，无法取消");
		}

		// 判断订单状态是不是待支付
		if (!order.getOrderStatus().equals(OrderStatusEnum.PENDING.getType())) {
			return R.ok("当前订单不是待支付状态，无法取消");
		}

		OrderInfo record = new OrderInfo();
		record.setId(orderInfo.getId());
		record.setCancelReason(orderInfo.getCancelReason());
		record.setOrderStatus(OrderStatusEnum.CANCELED.getType());
		this.updateById(record);
		return R.ok();
	}

	/**
	 * 订单退货
	 * @param orderInfo
	 * @return
	 */
	@Override
	public R orderReturn(OrderInfo orderInfo) {
		Long orderId = orderInfo.getId();
		OrderInfo order = this.getById(orderId);
		if (order == null) {
			return R.failed("订单不存在");
		}
		try {
			String message = checkOrderReturn(order);
			if (!StringUtils.isEmpty(message)) {
				return R.failed(message);
			}

			Map<String, String> resMap = WechatUtils.xcxRefund(orderId.toString(), orderId.toString(),
					order.getPayPrice(), order.getPayPrice(), "REFUND_SOURCE_UNSETTLED_FUNDS");
			if ("SUCCESS".equals(resMap.get("returnCode")) && "OK".equals(resMap.get("returnMsg"))) {
				// 统一下单成功
				resMap.remove("returnCode");
				resMap.remove("returnMsg");
				log.info("【小程序支付服务】退款成功！,进行退货逻辑");

				if (order.getOrderType().equals(OrderTypeEnum.SKU.getType())) {
					// 商品订单的场合
					return skuOrderReturn(order, orderInfo.getReturnReason());
				}
				else if (order.getOrderType().equals(OrderTypeEnum.EQUITY.getType())) {
					// 权益包的场合
					return equityOrderReturn(order, orderInfo.getReturnReason());
				}
				return R.ok();
			}
			else {
				log.info("【小程序支付服务】退款失败！原因:" + resMap.get("returnMsg"));
				return R.failed(resMap.get("returnMsg"));
			}
		}
		catch (Exception ex) {
			ex.printStackTrace();
			return R.failed("退款失败");
		}
	}

	/**
	 * 判断当前订单是否能退货
	 * @return
	 */
	private String checkOrderReturn(OrderInfo order) {
		if (order.getOrderType().equals(OrderTypeEnum.SKU.getType())) {
			// 商品订单的场合
			// 判断订单状态是不是待收货
			if (!order.getOrderStatus().equals(OrderStatusEnum.SHIPPED.getType())
					&& !order.getOrderStatus().equals(OrderStatusEnum.COMPLETE.getType())
					&& !order.getOrderStatus().equals(OrderStatusEnum.COMMENT.getType())) {
				return "当前订单状态变更，无法退货";
			}
		}
		else if (order.getOrderType().equals(OrderTypeEnum.EQUITY.getType())) {
			// 权益包的场合
			// 判断订单状态是不是待收货
			if (!order.getOrderStatus().equals(OrderStatusEnum.COMPLETE.getType())
					&& !order.getOrderStatus().equals(OrderStatusEnum.COMMENT.getType())) {
				return "当前订单状态变更，无法退货";
			}

			// 获取权益包订单详情
			List<OrderSkuDetail> orderSkuDetails = orderSkuDetailService
					.list(Wrappers.<OrderSkuDetail>lambdaQuery().eq(OrderSkuDetail::getOrderId, order.getId()));

			// 将权益包包含的优惠券设置成无效
			for (OrderSkuDetail skuDetail : orderSkuDetails) {
				Long equityId = skuDetail.getSpuId();
				ShopEquityVO vo = new ShopEquityVO();
				vo.setId(equityId);
				vo.setEquityOrderId(order.getId());
				R r = remoteShopCouponService.checkCancelEquityCoupons(vo, SecurityConstants.FROM_IN);
				if (r.getCode() == 1) {
					return r.getMsg();
				}
			}
		}
		return "";
	}

	/**
	 * 判断当前订单是否能退款
	 * @param order
	 * @return
	 */
	private String checkOrderRefund(OrderInfo order) {
		if (order.getOrderType().equals(OrderTypeEnum.SKU.getType())) {
			// 商品订单的场合
			// 判断订单状态是不是待发货
			if (!order.getOrderStatus().equals(OrderStatusEnum.PROCESSED.getType())) {
				return "当前订单状态变更，无法退货";
			}
		}
		return "";
	}

	/**
	 * sku退款
	 */
	private R skuOrderReturn(OrderInfo order, String returnReason) {
		// 判断订单是否使用优惠券
		if (!StringUtils.isEmpty(order.getCouponIds())) {
			// 获取优惠券信息
			String[] couponIds = order.getCouponIds().split(",");
			for (String couponId : couponIds) {
				// 用户领取的优惠券Id
				Long shopUserCouponId = Long.parseLong(couponId);
				remoteShopCouponService.returnShopUserCoupon(shopUserCouponId, SecurityConstants.FROM_IN);
			}
		}

		// 修改订单状态
		updateOrderReturnStatus(order, returnReason);
		return R.ok();
	}

	/**
	 * 权益包退款
	 * @param order
	 * @param returnReason
	 * @return
	 */
	private R equityOrderReturn(OrderInfo order, String returnReason) {

		// 获取权益包订单详情
		List<OrderSkuDetail> orderSkuDetails = orderSkuDetailService
				.list(Wrappers.<OrderSkuDetail>lambdaQuery().eq(OrderSkuDetail::getOrderId, order.getId()));

		// 将权益包包含的优惠券设置成无效
		orderSkuDetails.forEach(skuDetail -> {
			Long equityId = skuDetail.getSpuId();
			ShopEquityVO vo = new ShopEquityVO();
			vo.setId(equityId);
			vo.setEquityOrderId(order.getId());
			remoteShopCouponService.cancelEquityCoupons(vo, SecurityConstants.FROM_IN);
		});

		// 修改订单状态
		updateOrderReturnStatus(order, returnReason);
		return R.ok();
	}

	/**
	 * 退款修改状态
	 * @param order
	 * @param returnReason
	 */
	private void updateOrderReturnStatus(OrderInfo order, String returnReason) {

		OrderInfo record = new OrderInfo();
		record.setId(order.getId());
		// 修改订单状态为待发货
		record.setOrderStatus(OrderStatusEnum.RETURN.getType());
		// 设置退货时间
		record.setReturnTime(LocalDateTime.now());
		// 设置退款理由
		record.setReturnReason(returnReason);
		// 修改订单信息
		this.updateById(record);

		// 减去用户总金额
		handleUserOrderTotalChange(order, OperEnum.SUB.getType(), MoneyChangeRecordTypeEnum.RETURN_CASH.getType());
	}

	/**
	 * 继续支付
	 * @param orderInfo
	 * @return
	 */
	@Override
	public R rePay(OrderInfo orderInfo) {
		OrderInfo order = this.getById(orderInfo.getId());
		if (order == null) {
			return R.failed("当前订单不存在，无法继续支付");
		}

		// 判断订单状态是不是待支付
		if (!order.getOrderStatus().equals(OrderStatusEnum.PENDING.getType())) {
			return R.failed("当前订单状态发生改变，不是待支付状态，无法继续支付");
		}

		// 判断是否使用了优惠券
		if (!StringUtils.isEmpty(order.getCouponIds())) {
			// 获取优惠券信息
			String[] couponIds = order.getCouponIds().split(",");
			for (String couponId : couponIds) {
				// 判断优惠券是否可用
				ShopUserCoupon shopUserCoupon = new ShopUserCoupon();
				shopUserCoupon.setId(Long.parseLong(couponId));
				shopUserCoupon.setShopUserId(order.getShopUserId());
				R couponStatue = remoteShopCouponService.checkUserCouponStatue(shopUserCoupon,
						SecurityConstants.FROM_IN);
				if (couponStatue.getCode() == 1) {
					return couponStatue;
				}
			}
		}

		return R.ok();
	}

	/**
	 * 根据用户获取订单信息
	 * @param customToUserOrderSummaryDTO
	 * @return
	 */
	@Override
	public List<CustomToUserOrderSummaryVO> getCustomToUserOrderSummary(
			CustomToUserOrderSummaryDTO customToUserOrderSummaryDTO) {
		return baseMapper.getCustomToUserOrderSummary(customToUserOrderSummaryDTO);
	}

	@Override
	public R sendMq() {
		log.info("发送消息");
		rocketMQTemplate.convertAndSend("shop-user-point-change", "Hello, World!");
		log.info("消息发送成功");
		return null;
	}

}
